#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
# 作者：肖银皓
# 创建：2021-06-13
# 用意：生成HTML报告
"""
import json
import os

class BeautifulReport(object):
    def __init__(self):
        self.title = '缺陷检测报告'
        self.filename = 'Report.html'
        self.FIELDS = None

    def set_fields(
            self,
            fileds):
        self.FIELDS = fileds

    def report(
            self,
            description,
            filename,
            log_path,
            report_temp):
        """
        生成测试报告,并放在当前运行路径下
        :param log_path: 生成report的文件存储路径
        :param filename: 生成文件的filename
        :param description: 生成文件的注释
        :return:
        """
        if filename:
            self.filename = filename if filename.endswith(
                '.html') else filename + '.html'

        if description:
            self.title = description

        self.log_path = os.path.abspath(log_path)

        self.output_report(report_temp)

    # 运行一个suit重写一次
    def output_report(self, template_path):
        """
        生成测试报告到指定路径下
        :return:
        """
        override_path = os.path.abspath(self.log_path) if \
            os.path.abspath(self.log_path).endswith('/') else \
            os.path.abspath(self.log_path) + '/'

        with open(template_path, 'rb') as file:
            body = file.readlines()
        file.close()
        with open(override_path + self.filename, 'wb') as write_file:
            for item in body:
                if item.strip().startswith(b'var resultData'):
                    head = '    var resultData = '
                    item = item.decode().split(head)
                    item[1] = head + \
                              json.dumps(self.FIELDS, ensure_ascii=False, indent=4)
                    item = ''.join(item).encode()
                    item = bytes(item) + b';\n'
                write_file.write(item)
            write_file.close()
